package com.thingple.web.bridge.reader;

import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;

import com.thingple.eye.ActionResultListener;
import com.thingple.h5.bridge.Bridge;
import com.thingple.h5.bridge.BridgeConfig;
import com.thingple.h5.bridge.JsInvokeHandler;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 读卡后,处理
 * Created by lism on 2017/8/18.
 */

class WriteCardListener implements ActionResultListener {

    private WebView webView;

    private Bridge jsBridge;

    private String callback;

    WriteCardListener(WebView webView, Bridge jsBridge, String callbackFunc) {

        this.webView = webView;
        this.jsBridge = jsBridge;
        this.callback = callbackFunc;
    }

    private void afterWriteCard(String code, String msg, String tid) {
        BridgeConfig bridgeConfig = jsBridge.getClass().getAnnotation(BridgeConfig.class);
        if (bridgeConfig == null) {
            return;
        }
        Map<String, String> paramMap = new HashMap<>();
        if (code != null) {
            paramMap.put("code", code);
        }
        if (msg != null) {
            paramMap.put("message", msg);
        }

        if (tid == null) {
            tid = "";
        }
        paramMap.put("tid", tid);
        JsInvokeHandler jsInvokeHandler = new JsInvokeHandler(webView);
        jsInvokeHandler
                .function(callback)
                .params(paramMap)
                .invoke();
    }

    @Override
    public void onResponse(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                String code = bundle.getString("code");
                String message = bundle.getString("message");
                String tid = bundle.getString("tid");
                afterWriteCard(code, message, tid);
            }
        }
    }
}
